# cython: language_level=3
import time
import cv2 as cv
from threading import Thread

class CamWidget:
	def __init__(self,path):
		self.cap = cv.VideoCapture(path)


		self.cap.set(3,640)
		self.cap.set(4,480)

		self.cap.set(cv.CAP_PROP_FPS, 30)

		self.thread_release=False

		self.path=path
		self.image=None

		self.thread = Thread(target=self.read_image, args=())
		self.thread.daemon = True
		self.thread.start()

		while self.image is None:
			time.sleep(0.1)

	def read_image(self):
		while True:
			if self.thread_release==False:

				ret,image = self.cap.read()
				if ret==False:
					self.cap.release()
					print("read_video_error")
					self.cap = cv.VideoCapture(self.path)
					t1=time.time()
					while self.cap.isOpened()==False:
						if time.time()-t1>2:
							self.cap.release()
							self.cap = cv.VideoCapture(self.path)
							t1=time.time()
				else:
					self.image=image
			else:
				self.cap.release()
				break

	def close(self):
		self.thread_release=True
		self.thread.join()
